<?php

/**
 * @property int $address_id
 * @property int $user_id
 * @property string $type
 * @property string $street
 * @property string $street2
 * @property string $city
 * @property string $state
 * @property string $country
 * @property string $zip
 * @property datetime $added
 * @property datetime $updated
 */
class Address extends Am_Record
{
    const TYPE_TAX = 'tax'; // To keep address history records for invoice payments tax and refunds
    const TYPE_DEFAULT = 'default'; // To keep address history records for invoice payments tax and refunds
    const TYPE_ANY = 'any';
}

class AddressTable extends Am_Table_WithData
{
    protected $_key = 'address_id';
    protected $_table = '?_address';
    protected $_recordClass = 'Address';
    protected $fields = ['name_f', 'name_l', 'street', 'street2', 'city', 'state', 'zip', 'country'];

    /**
     * @param User|array $address
     */
    function hash($address): string
    {
        if ($address instanceof User) {
            $address = $address->toArray();
        }
        $hash = '';
        foreach ($this->fields as $v) {
            $hash .= $address[$v] ?? "";
        }
        $hash = md5(strtoupper($hash));
        return $hash;
    }

    /**
     * For now get default address from ?_user table
     * Later it should be stored in address table too;
     */
    function getDefaultAddress(User $user): ?array
    {
        $address = [];
        foreach ($this->fields as $field) {
            $address[$field] = $user->get($field);
        }
        if (empty(array_filter($address))) {
            return null;
        }

        return $address;
    }

    /**
     * Try to find address in table first,
     * if there is no such address create from User profile and return it ID
     */
    function getTaxAddressId(User $user): ?int
    {
        $addressInfo = $this->getDefaultAddress($user);

        if (empty($addressInfo)) {
            return null;
        }

        $hash = $this->hash($addressInfo);
        $search = [
            'user_id' => $user->pk(),
            'hash' => $hash,
            'type'=> Address::TYPE_TAX
        ];

        $address = $this->findFirstBy($search);

        if (empty($address)) {
            $address = $this->createRecord($addressInfo);
            $address->user_id = $user->pk();
            $address->added = $this->getDi()->sqlDateTime;
            $address->updated = $this->getDi()->sqlDateTime;
            $address->hash = $hash;
            $address->type = Address::TYPE_TAX;
            $address->insert();
        }

        return !empty($address) ? $address->pk() : null;
    }

    function anonymize(User $user, $haveTax): void
    {
        foreach ($this->findBy(['user_id' => $user->pk()]) as $address) {
            foreach ($this->fields as $field) {
                if ($haveTax && ($field == 'country'))
                    continue;
                $address->set($field, '');
            }
            $address->save();
        }
    }
}